<template>
  <div>
    socket is loading...
  </div>
</template>

<script>
import Stomp from 'stompjs'
import { ActiveMQ } from '@/constants/active-mq'
import { getToken } from '@/utils/auth'
import { logout } from '@/api/user'
import { MessageType } from '@/constants/message-type'
import { RabbitMQ } from '@/constants/rabbit-mq'
import { get } from '@/api/base-api'

export default {
  name: 'StompMq',
  data() {
    return {
      momType: 0,
      client: null
    }
  },
  created() {
    get('UserManagement/GetMomType', null).then(response => {
      this.momType = parseInt(response.object)
      this.client = this.momType === 0
        ? Stomp.client(ActiveMQ.ConnectionString)
        : Stomp.client(RabbitMQ.Service)
      this.connect()
    })
  },
  mounted() {
  },
  methods: {
    onConnected: function(frame) {
      console.log('Connected: ' + frame)
      const topic = this.momType === 0
        ? '/topic/' + ActiveMQ.TopicName + ActiveMQ.MessagePrefix
        : '/exchange/' + RabbitMQ.ExchangeName + '/' + RabbitMQ.QueueName
      this.client.subscribe(topic, this.responseCallback, this.onFailed)
    },
    onFailed: function(frame) {
      console.log('Failed: ' + frame)
    },
    responseCallback: function(frame) {
      // console.log('responseCallback msg=>' + frame.body)
      console.log('------')
      const message = JSON.parse(decodeURIComponent(frame.body))
      if (message.MessageType === MessageType.ForceLogout) {
        const id = message.Object.Id
        const user = JSON.parse(sessionStorage.getItem(getToken()))
        if (id === user.id) {
          this.$alert('您好，您被管理员强制下线！', '系统强制下线通知', {
            confirmButtonText: '确定',
            showClose: false,
            callback: action => {
              logout(getToken())
              location.reload(true)
            }
          })
        }
      }
    },
    connect: function() {
      const headers = {
        login: this.momType === 0 ? ActiveMQ.UserName : RabbitMQ.UserName,
        passcode: this.momType === 0 ? ActiveMQ.Password : RabbitMQ.Password
      }
      this.client.connect(headers, this.onConnected, this.onFailed)
    }
  }
}
</script>

<style scoped>

</style>
